package com.c2b.algorithm.leetcode.jzoffer;

/**
 * <a href="https://leetcode.cn/problems/he-bing-liang-ge-pai-xu-de-lian-biao-lcof/">合并两个排序的链表</a>
 * <p>输入两个递增的链表，单个链表的长度为n，合并这两个链表并使新链表中的节点仍然是递增排序的。</p>
 * <pre>
 *     示例1：
 *          输入：1->2->4, 1->3->4
 *          输出：1->1->2->3->4->4
 * </pre>
 *
 * @author c2b
 * @since 2023/3/7 15:13
 */
public class JzOffer0025MergeTwoLists_S {

    public ListNode mergeTwoLists(ListNode list1, ListNode list2) {
        if (list1 == null || list2 == null) {
            return list1 == null ? list2 : list1;
        }
        // 用一个虚拟链表来记录合并后的链表
        ListNode dummy = new ListNode(-1);
        ListNode currentNode = dummy;
        while (list1 != null && list2 != null) {
            if (list1.val <= list2.val) {
                currentNode.next = list1;
                list1 = list1.next;
            } else {
                currentNode.next = list2;
                list2 = list2.next;
            }
            currentNode = currentNode.next;
        }
        if (list1 == null) {
            currentNode.next = list2;
        }
        if (list2 == null) {
            currentNode.next = list1;
        }
        return dummy.next;
    }

    public static void main(String[] args) {
        ListNode listNode1 = new ListNode(-1);
        listNode1.next = new ListNode(2);
        listNode1.next.next = new ListNode(4);
        ListNode listNode2 = new ListNode(1);
        listNode2.next = new ListNode(3);
        listNode2.next.next = new ListNode(4);
        JzOffer0025MergeTwoLists_S jzOffer0025Merge = new JzOffer0025MergeTwoLists_S();
        ListNode merge = jzOffer0025Merge.mergeTwoLists(null, null);
    }
}
